local awful   = require("awful")
local naughty = require("naughty")
require("main.vars")


function read_dev_state(dev)
   local f = io.open(statesPath..dev.."Notify", "r+")
   local state = 0

   if not f then
      f = io.open(statesPath..dev.."Notify", "w")
      f:write("1")
      state = 1
   else
      state = f:read()
      state = tonumber(state)
   end
   f:close()

   return state
end

function notify_dev(dev, devstate)
   local devNoti = ""
   local devText = ""

   if dev == "wacom" then
      devNoti = "Wacom"
      devText = "Screen changed"
   elseif dev == "touchpad" then
      devNoti = "Touchpad"
      devText = devstate == 1 and "on" or "off"
   end

   if read_dev_state(dev) == 1 then
      naughty.notify({
         title        = devNoti.." state",
         text         = devText,
         timeout      = 1,
         position     = "bottom_right",
         border_width = 4,
      })
   end
end

function toggle_dev_notify(dev)
   local devNoti = ""
   local devName = ""

   if dev == "wacom" then
      devNoti = "wacomNotify"
      devName = "Wacom"
   elseif dev == "touchpad" then
      devNoti = "touchpadNotify"
      devName = "Touchpad"
   end

   local f = io.open(statesPath..devNoti, "r+")
   local state = 0

   if not f then
      f = io.open(statesPath..devNoti, "w")
      f:write("1")
      state = 1
   else
      state = (tonumber(f:read()) + 1) % 2
      f:seek("set",0)
      f:write(state)
   end

   naughty.notify({
         title        = devName.." state notify",
         text         = state == 1 and "on" or "off",
         timeout      = 1,
         position     = "bottom_right",
         border_width = 4,
   })
   f:close()
end

function update_dev(dev)
   if dev == "touchpad" then
      local f = io.open(statesPath.."touchpadState", "r+")
      if not f then
         f = io.open(statesPath.."touchpadState", "w")
         f:write("0")
      else
          local before = (tonumber(f:read()) + 1) % 2

          awful.spawn("xinput set-prop 'GXTP7863:00 27C6:01E0 Touchpad' 'Device Enabled' "..before)
          notify_dev("touchpad", before)
          f:seek("set", 0)
          f:write(before)
      end
      f:close()
   elseif dev == "wacom" then
      awful.spawn("xsetwacom --set 'Wacom One by Wacom M Pen stylus' MapToOutput next")
      notify_dev("wacom", 0)
   end
end
